﻿using AbpApplication.Expand;
using AbpEntityFrameworkcore.DbContext;
using AbpToDomain.EntityInfo;
using Application.Expand;
using Mesosphere.Dto;
using Mesosphere.InPut;
using Microsoft.EntityFrameworkCore;
using S7.Net.Types;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using DateTime = System.DateTime;

namespace AbpApplication.AppServices
{
    public class ConsumerService : ApplicationService, IConsumerService
    {

        private readonly IRepository<TaskOrder> taskorder_res;
        private readonly IRepository<NeetOutMaterial> neetout_res;
        private readonly IRepository<MaterialBase> material_res;
        private readonly IRepository<NeetOutMaterial> neetoutmaterial_res;
        private readonly IRepository<PutInOrder> put_in_res;
        private readonly IRepository<PutOutOrder> put_out_res;
        private readonly MyDbContext dbContext;
        private readonly IRepository<MaterialProperty> MaterialProperty_res;
        private readonly ILoginHelper loginHelper;
        private readonly IRepository<CustomCheckList> CustomCheckList_res;

        public ConsumerService(IRepository<TaskOrder> taskorder_res,
            IRepository<NeetOutMaterial> neetout_res,
            IRepository<MaterialBase> material_res,
            IRepository<NeetOutMaterial> neetoutmaterial_res, ILoginHelper loginHelper,
IRepository<MaterialProperty> materialProperty_res, IRepository<PutInOrder> put_in_res, MyDbContext dbContext, IRepository<PutOutOrder> put_out_res, IRepository<CustomCheckList> customCheckList_res)

        {
            this.taskorder_res = taskorder_res;
            this.neetout_res = neetout_res;
            this.material_res = material_res;
            this.neetoutmaterial_res = neetoutmaterial_res;
            this.loginHelper = loginHelper;
            MaterialProperty_res = materialProperty_res;
            this.put_in_res = put_in_res;
            this.dbContext = dbContext;
            this.put_out_res = put_out_res;
            this.CustomCheckList_res = customCheckList_res;
        }

        public async Task<ApiResponse> CreateInBoundOrder(InPut_CunsumerService InPut)
        {
            try
            {
                var PutInorderDataList = await put_in_res.WithDetails().ToListAsync();
                bool Check_res = PutInorderDataList.Any(x => InPut.putInOrderDtos. Any(y => y.Consumer_MaterialId == x.Consumer_MaterialId));

                if (Check_res)
                {
                    var Check_res5 = PutInorderDataList.Where(x => InPut.putInOrderDtos.Any(y => y.Consumer_MaterialId == x.Consumer_MaterialId)).ToList();
                    return new ApiResponse("WMS已存在相同Id的入库清单", false, Check_res5.Select(x=>x.Consumer_MaterialId));
                }
                bool Check_res2 = PutInorderDataList.Any(x => x.Symbol==InPut.Symbol);
                if (Check_res2)
                {
                    return new ApiResponse("WMS已存在相同清单号", false, null);
                }
                List<PutInOrder> putInOrderModel = ObjectMapper.Map<List<PutInOrderDto>, List<PutInOrder>>(InPut.putInOrderDtos);
                putInOrderModel.ForEach(x =>
                {
                    x.Symbol = InPut.Symbol;
                    x.State = "待入库";
                    x.CreateTime = System.DateTime.Now;
                });
                await put_in_res.InsertManyAsync(putInOrderModel);
                return new ApiResponse("添加成功", true, null);
            }
            catch (Exception ex)
            {


                loginHelper.LoginAsync(InPut, "Error-CreateInBoundOrder");
                return new ApiResponse("Error-CreateInBoundOrder", false, null);
            }
        }

        public async Task<ApiResponse> CreateOutBoundOrder(InPut_CunsumerService2 InPut)
        {
            try
            {
                var Symbol = System.String.Join("-", InPut.putOutOrder_Lists?.Select(order => order.PutOutOrderCode) ?? Enumerable.Empty<string>());
                var PutOutorderDataList = await put_out_res.WithDetails().ToListAsync();
                bool Check_res = PutOutorderDataList.Any(x => x.Symbol == Symbol);
                if (Check_res)
                {
                    return new ApiResponse("WMS已存在相同出库清单号", false, null);
                }
              //if(  ! Guid.TryParse(InPut.OrderBatch, out _))
              //  {
              //      return new ApiResponse("批次号是无法识别的guid", false, null);
              //  }

                if (InPut.Machine!=1&& InPut.Machine != 2)
                {
                    return new ApiResponse("WMS机台号错误", false, null);
                }
                List<PutOutOrder> putOutOrderModel=new List<PutOutOrder>();
                foreach (var item in InPut.putOutOrder_Lists)
                {
                    List<PutOutOrder> putOutOrderModelsingle = ObjectMapper.Map<List<PutOutOrderDto>, List<PutOutOrder>>(item.outOrderDtos);
                    putOutOrderModelsingle.ForEach(x => x.PutOutOrderCode = item.PutOutOrderCode);
                    putOutOrderModel.AddRange(putOutOrderModelsingle);
                }
                int no = 0;
              
                putOutOrderModel.ForEach(x =>
                {
                    x.Symbol = Symbol;                    
                    x.State = "待分配";
                    x.IsReplenishment = false;
                    x.CreateTime = System.DateTime.Now;
                    x.No = 1+no;
                    x.Machine= InPut.Machine;
                    x.VirtualOutBound=x.OutBoundQuantity;
                    x.OrderBatch = InPut.OrderBatch;
                    x.printOrder=InPut.printOrder;
                    no++;
                });
                loginHelper.LoginInfoAsync(InPut, $"出库订单{InPut.OrderBatch}");
                await put_out_res.InsertManyAsync(putOutOrderModel);
                return new ApiResponse("添加成功", true, null);
            }
            catch (Exception ex)
            {


                loginHelper.LoginAsync(InPut, "Error-CreateOutBoundOrder");
                return new ApiResponse("Error-CreateOutBoundOrder", false, null);
            }
        }

        public async Task<ApiResponse> GetMaterialInfo(InPut_CunsumerService3 InPut)
        {
            throw new NotImplementedException();
        }

        public async Task<ApiResponse> MakeInventory(InPut_CunsumerService4 InPut)
        {
            throw new NotImplementedException();
        }

        public async Task<ApiResponse> MaterialCheck(InPut_CunsumerService5 InPut)
        {
           List<CustomCheckList> customCheckLists=  await dbContext.customCheckLists.Where(x => InPut.Consumer_MaterialIds.Any(y => y == x.Consumer_MaterialId)
                                              &&x.IsCheck==false).ToListAsync();
            if (customCheckLists.Count > 0)
            {
                return new ApiResponse("WMS已存在相同的物料Id未检查", false, customCheckLists.Select(x=>x.Consumer_MaterialId));
            }
            //create coustomCheckList
            List<CustomCheckList> CustomCheckListModel= new List<CustomCheckList>();
           foreach (var item in InPut.Consumer_MaterialIds)
            {
                CustomCheckList customCheckList = new CustomCheckList();
                customCheckList.Consumer_MaterialId = item;
                customCheckList.CreateTime = DateTime.Now;
                customCheckList.IsCheck = false;
                customCheckList.CreateTime = DateTime.Now;
                CustomCheckListModel.Add(customCheckList);
            }
            await dbContext.AddRangeAsync(CustomCheckListModel);
            await dbContext.SaveChangesAsync();
            return new ApiResponse("添加成功", true, null);
        }
    }
}
